package com.sanjishu.enterlab.electricity.sale.service;

import com.sanjishu.enterlab.electricity.sale.controller.Response;
import com.sanjishu.enterlab.electricity.sale.domain.*;
import com.sanjishu.enterlab.electricity.sale.mapper.*;
import com.sanjishu.enterlab.electricity.sale.utils.Page;
import com.sanjishu.enterlab.electricity.sale.utils.PageRequest;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class SaleApplyService {

    @Autowired
    private SaleApplyMapper saleApplyMapper;
    @Autowired
    private CompanyBakMapper companyBakMapper;
    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    @Autowired
    private DetailInfoMapper detailInfoMapper;
    @Autowired
    private ContractInfoMapper contractInfoMapper;
    @Value("${page.size}")
    private Integer pageSize;

    public SaleApply findByUserId(Integer userId, Integer companyInfoId) {
        return saleApplyMapper.findNewByUserId(userId, companyInfoId);
    }

    public SaleApply createApply(Integer userId, Integer companyInfoId) {
        SaleApply saleApply = new SaleApply();
        saleApply.setUserId(userId);
        saleApply.setCompanyInfoId(companyInfoId);
        saleApply.setStatus(SaleApply.STATUS_NORMAL);
        saleApply.setCreatedAt(new Date());
        saleApplyMapper.insert(saleApply);
        return saleApply;
    }

    public Page<SaleApply> newSaleApply(Integer page) {
        Long count = saleApplyMapper.countNewApply();
        if (count == 0) {
            return new Page<SaleApply>(new PageRequest(1, pageSize), new ArrayList<>(), count);
        }
        PageRequest request = new PageRequest(page, pageSize);
        List<SaleApply> result = saleApplyMapper.findNewApply(request);
        Page<SaleApply> pageData = new Page<SaleApply>(request, result, count);
        if (pageData.getCurrentPage() > pageData.getTotalPage()) {
            request = new PageRequest(pageData.getTotalPage(), pageSize);
            result = saleApplyMapper.findNewApply(request);
            pageData = new Page<>(request, result, count);
        }
        return pageData;
    }

    public void passApply(String[] companyUsers) {
        HashMap<Integer, Integer> maps = returnApplyUsers(companyUsers);
        if (maps != null && maps.keySet() != null) {
            List<SaleApply> saleApplyList = saleApplyMapper.findByCompanyIds(maps.keySet());
            List<CompanyBak> companyBakList = companyBakMapper.updateSaleId(maps.keySet());
            HashMap<Integer, CompanyBak> companyBakHashMap = new HashMap<>();
            if (companyBakList != null && companyBakList.size() > 0) {
                for (CompanyBak companyBak : companyBakList) {
                    companyBakHashMap.put(companyBak.getId(), companyBak);
                }
            }
            if (saleApplyList != null && saleApplyList.size() > 0) {
                for (SaleApply saleApply : saleApplyList) {
                    Integer userId = maps.get(saleApply.getCompanyInfoId());
                    if (userId.equals(saleApply.getUserId())) {
                        saleApply.setStatus(SaleApply.STATUS_VERIFIED);
                        saleApplyMapper.updateByPrimaryKey(saleApply);
                        if (companyBakHashMap != null && companyBakHashMap.get(saleApply.getCompanyInfoId()) != null) {
                            CompanyBak cBak = companyBakHashMap.get(saleApply.getCompanyInfoId());
                            cBak.setUserId(userId);
                            cBak.setRelatedAt(new Date());
                            companyBakMapper.updateByPrimaryKey(cBak);
                        }
                    } else {
                        saleApply.setStatus(SaleApply.STATUS_UNVERIFIED);
                        saleApplyMapper.updateByPrimaryKey(saleApply);
                    }
                }
            }
        }
    }

    @Transactional
    public void passApplyAuto(Integer applyId, Integer userId, Integer companyBakId) {
        SaleApply saleApply = saleApplyMapper.selectByPrimaryKey(applyId);
        saleApply.setStatus(SaleApply.STATUS_VERIFIED);
        saleApplyMapper.updateByPrimaryKey(saleApply);
        CompanyBak companyBak = companyBakMapper.selectByPrimaryKey(companyBakId);
        companyBak.setUserId(userId);
        companyBak.setRelatedAt(new Date());
        companyBakMapper.updateByPrimaryKey(companyBak);
    }

    public void refuseApply(String[] companyUsers) {
        HashMap<Integer, List<Integer>> maps = returnRefuseUsers(companyUsers);
        if (maps != null && maps.keySet() != null) {
            List<SaleApply> saleApplyList = saleApplyMapper.findByCompanyIds(maps.keySet());
            if (saleApplyList != null && saleApplyList.size() > 0) {
                for (SaleApply saleApply : saleApplyList) {
                    List<Integer> userIdList = maps.get(saleApply.getCompanyInfoId());
                    if (userIdList.contains(saleApply.getUserId())) {
                        saleApply.setStatus(SaleApply.STATUS_UNVERIFIED);
                        saleApplyMapper.updateByPrimaryKey(saleApply);
                    }
                }
            }
        }
    }

    public HashMap<Integer, Integer> returnApplyUsers(String[] companyUsers) {
        HashMap<Integer, Integer> maps = new HashMap<>();
        if (companyUsers != null && companyUsers.length > 0) {
            for (String str : companyUsers) {
                String companyId = "";
                String userId = "";
                if (str != "") {
                    String[] strTemp = str.split("_");
                    if (strTemp.length == 2) {
                        companyId = strTemp[0];
                        userId = strTemp[1];
                    }
                }
                if (companyId != "" && userId != "") {
                    maps.put(new Integer(companyId), new Integer(userId));
                }

            }
        }
        return maps;
    }

    public HashMap<Integer, List<Integer>> returnRefuseUsers(String[] companyUsers) {
        HashMap<Integer, List<Integer>> maps = new HashMap<>();
        if (companyUsers != null && companyUsers.length > 0) {
            for (String str : companyUsers) {
                String companyId = "";
                String userId = "";
                if (str != "") {
                    String[] strTemp = str.split("_");
                    if (strTemp.length == 2) {
                        companyId = strTemp[0];
                        userId = strTemp[1];
                    }
                }
                if (companyId != "" && userId != "") {
                    List<Integer> userIdList = maps.get(new Integer(companyId));
                    if (userIdList == null || userIdList.size() == 0) {
                        userIdList = new ArrayList<>();
                    }
                    userIdList.add(new Integer(userId));
                    maps.put(new Integer(companyId), userIdList);
                }

            }
        }
        return maps;
    }

    public Page<SaleApply> fineSaleApplyByPage(Integer userId, String searchText, Integer searchTypes, Integer page, Integer currentSize) {
        Long count = count = saleApplyMapper.countSaleCompanies(userId, searchText, searchTypes);
        if (currentSize == 0) {
            currentSize = pageSize;
        }
        if (count == 0) {
            return new Page<SaleApply>(new PageRequest(1, currentSize), new ArrayList<>(), count);
        }

        PageRequest request = new PageRequest(page, currentSize);
        List<SaleApply> result = result = saleApplyMapper.findSaleRelevance(userId, searchText, searchTypes, request);
        Page<SaleApply> pageData = new Page<SaleApply>(request, result, count);

        if (pageData.getCurrentPage() > pageData.getTotalPage()) {
            request = new PageRequest(pageData.getTotalPage(), currentSize);
            result = saleApplyMapper.findSaleRelevance(userId, searchText, searchTypes, request);
            pageData = new Page<>(request, result, count);
        }

        return pageData;
    }

    public Response cancelApply(Integer userId, Integer applyId) {
        SaleApply saleApply = saleApplyMapper.selectByPrimaryKey(applyId);
        if (saleApply != null) {
            CompanyInfo companyInfo = companyInfoMapper.findByCompanyBakId(saleApply.getCompanyInfoId());
            if (companyInfo != null && userId.equals(companyInfo.getAdminId()) && companyInfo.getStatus() != CompanyInfo.STATUS_SIGNED) {
                //return Response.getError("当前企业已经生成合同，不能再取消了。");
                DetailInfo detailInfo = detailInfoMapper.findByCompanyId(companyInfo.getId());
                ContractInfo contractInfo = contractInfoMapper.findByCompanyAndTime(companyInfo.getId());
                detailInfoMapper.deleteByPrimaryKey(detailInfo.getId());
                contractInfoMapper.deleteByPrimaryKey(contractInfo.getId());
                companyInfoMapper.deleteByPrimaryKey(companyInfo.getId());
            }
            CompanyBak companyBak = companyBakMapper.selectByPrimaryKey(saleApply.getCompanyInfoId());
            if (companyBak != null && companyBak.getUserId() != null && userId.equals(companyBak.getUserId())) {
                companyBak.setUserId(null);
                companyBakMapper.updateByPrimaryKey(companyBak);
            }
            saleApply.setStatus(SaleApply.STATUS_CANCELED);
            saleApplyMapper.updateByPrimaryKey(saleApply);
        }
        return Response.buildSuccess("取消成功。");
    }
}